import { Button, Input, Upload, message, Card, Descriptions, Avatar, Form, Select, DatePicker } from 'antd'
import './UserInfo.css'
import { LoadingOutlined, PlusOutlined, UserOutlined, EditOutlined, SaveOutlined, CloseOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { useUserStore } from '../store/user.js';
import { defaultAvatar } from '../constant/index.js';
import dayjs from 'dayjs';
const { TextArea } = Input;
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
    }
    return isJpgOrPng && isLt2M;
};

export default function UserInfo() {
    const user = useUserStore(state => state.user);
    const login = useUserStore(state => state.login);

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const [isEditing, setIsEditing] = useState(false);
    const [form] = Form.useForm();
    const [messageApi, contextHolder] = message.useMessage();

    // 初始化表单数据
    useEffect(() => {
        if (user) {
            form.setFieldsValue({
                userName: user.userName,
                userProfile: user.userProfile,
                email: user.email,
                phone: user.phone,
                gender: user.gender,
                birthday: user.birthday ? dayjs(user.birthday) : null
            });
            setImageUrl(user.userAvatar);
        }
    }, [user, form]);

    /**
    * 处理文件上传状态变化的回调函数
    */
    const handleChange = info => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // 实际项目中应该从响应中获取URL
            getBase64(info.file.originFileObj, url => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };

    // 保存用户信息
    const handleSave = async () => {
        try {
            const values = await form.validateFields();

            // 构建更新的用户信息
            const updatedUser = {
                ...user,
                userName: values.userName,
                userProfile: values.userProfile,
                email: values.email,
                phone: values.phone,
                gender: values.gender,
                birthday: values.birthday ? values.birthday.format('YYYY-MM-DD') : null,
                userAvatar: imageUrl
            };

            // 更新用户状态
            login(updatedUser);

            messageApi.success('个人信息保存成功！');
            setIsEditing(false);
        } catch (error) {
            messageApi.error('请检查输入信息是否正确');
        }
    };

    // 取消编辑
    const handleCancel = () => {
        // 重置表单到原始值
        form.setFieldsValue({
            userName: user.userName,
            userProfile: user.userProfile,
            email: user.email,
            phone: user.phone,
            gender: user.gender,
            birthday: user.birthday ? dayjs(user.birthday) : null
        });
        setImageUrl(user.userAvatar);
        setIsEditing(false);
    };

    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传头像</div>
        </button>
    );

    if (!user) {
        return (
            <div id='userInfo'>
                <Card style={{ width: '100%', maxWidth: 600, margin: '0 auto' }}>
                    <div style={{ textAlign: 'center', padding: '40px 0' }}>
                        <UserOutlined style={{ fontSize: '48px', color: '#ccc' }} />
                        <p style={{ marginTop: '16px', color: '#666' }}>请先登录查看个人信息</p>
                    </div>
                </Card>
            </div>
        );
    }

    return (
        <div id='userInfo'>
            {contextHolder}
            <div className='user-info-container'>
                {/* 用户基本信息卡片 */}
                <Card
                    className='user-basic-card'
                    title={
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <span>个人信息</span>
                            <Button
                                type={isEditing ? 'default' : 'primary'}
                                icon={isEditing ? <CloseOutlined /> : <EditOutlined />}
                                onClick={() => isEditing ? handleCancel() : setIsEditing(true)}
                            >
                                {isEditing ? '取消编辑' : '编辑信息'}
                            </Button>
                        </div>
                    }
                >
                    <div className='user-info-content'>
                        {/* 头像区域 */}
                        <div className='avatar-section'>
                            <Avatar
                                size={120}
                                src={imageUrl || user.userAvatar || defaultAvatar}
                                icon={<UserOutlined />}
                            />
                            {isEditing && (
                                <Upload
                                    name="avatar"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
                                    beforeUpload={beforeUpload}
                                    onChange={handleChange}
                                    style={{ marginTop: '16px' }}
                                >
                                    <Button icon={loading ? <LoadingOutlined /> : <PlusOutlined />}>
                                        {loading ? '上传中' : '更换头像'}
                                    </Button>
                                </Upload>
                            )}
                        </div>

                        {/* 信息区域 */}
                        <div className='info-section'>
                            {!isEditing ? (
                                // 查看模式
                                <Descriptions column={1} labelStyle={{ width: '100px', fontWeight: 'bold' }}>
                                    <Descriptions.Item label="用户名">{user.userName || '未设置'}</Descriptions.Item>
                                    <Descriptions.Item label="账号">{user.userAccount}</Descriptions.Item>
                                    <Descriptions.Item label="角色">{user.userRole === 'admin' ? '管理员' : '普通用户'}</Descriptions.Item>
                                    <Descriptions.Item label="邮箱">{user.email || '未设置'}</Descriptions.Item>
                                    <Descriptions.Item label="手机号">{user.phone || '未设置'}</Descriptions.Item>
                                    <Descriptions.Item label="性别">
                                        {user.gender === 1 ? '男' : user.gender === 2 ? '女' : '未设置'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="生日">{user.birthday || '未设置'}</Descriptions.Item>
                                    <Descriptions.Item label="个人简介">
                                        <div style={{ maxWidth: '300px', wordBreak: 'break-word' }}>
                                            {user.userProfile || '这个人很懒，什么都没有留下...'}
                                        </div>
                                    </Descriptions.Item>
                                    <Descriptions.Item label="注册时间">
                                        {user.createTime ? dayjs(user.createTime).format('YYYY-MM-DD HH:mm') : '未知'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="最后登录">
                                        {user.lastLoginTime ? dayjs(user.lastLoginTime).format('YYYY-MM-DD HH:mm') : '未知'}
                                    </Descriptions.Item>
                                </Descriptions>
                            ) : (
                                // 编辑模式
                                <Form form={form} layout="vertical" style={{ width: '100%' }}>
                                    <Form.Item
                                        label="用户名"
                                        name="userName"
                                        rules={[{ required: true, message: '请输入用户名' }]}
                                    >
                                        <Input placeholder="请输入用户名" />
                                    </Form.Item>

                                    <Form.Item label="邮箱" name="email">
                                        <Input type="email" placeholder="请输入邮箱" />
                                    </Form.Item>

                                    <Form.Item label="手机号" name="phone">
                                        <Input placeholder="请输入手机号" />
                                    </Form.Item>

                                    <Form.Item label="性别" name="gender">
                                        <Select placeholder="请选择性别">
                                            <Select.Option value={0}>未设置</Select.Option>
                                            <Select.Option value={1}>男</Select.Option>
                                            <Select.Option value={2}>女</Select.Option>
                                        </Select>
                                    </Form.Item>

                                    <Form.Item label="生日" name="birthday">
                                        <DatePicker placeholder="请选择生日" style={{ width: '100%' }} />
                                    </Form.Item>

                                    <Form.Item label="个人简介" name="userProfile">
                                        <TextArea rows={4} placeholder="介绍一下自己吧..." />
                                    </Form.Item>

                                    <Form.Item>
                                        <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
                                            <Button onClick={handleCancel}>取消</Button>
                                            <Button type="primary" icon={<SaveOutlined />} onClick={handleSave}>
                                                保存
                                            </Button>
                                        </div>
                                    </Form.Item>
                                </Form>
                            )}
                        </div>
                    </div>
                </Card>
            </div>
        </div>
    )
}